package cn.tedu._03vehicle.base.exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolationException;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult handleIllegalArgumentException(IllegalArgumentException e) {
        log.error("参数错误：{}", e.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED, e.getMessage());
    }

    @ExceptionHandler
    public JsonResult handleRuntimeException(RuntimeException e) {
        String data = e.getMessage();
        log.error("服务器发生异常：{}", data);
        log.error("RuntimeException={}", e);
        return new JsonResult(StatusCode.OPERATION_FAILED, data);
    }
    @ExceptionHandler
    public JsonResult handleConstraintViolationException(ConstraintViolationException e) {
        String data = e.getMessage();
        String message = data.split(":")[1].trim();
        log.error("ConstraintViolationException：{}", message);
        return new JsonResult(StatusCode.THROWABLE_ERROR, message);
    }

    @ExceptionHandler
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String data = e.getFieldError().getDefaultMessage();
        log.error("请求参数异常：{}", data);
        return new JsonResult(StatusCode.VALIDATE_ERROR, data);
    }
    /*@ExceptionHandler
    public JsonResult handleException(Throwable e) {
        String data = e.getMessage();
        log.error("服务器发生异常：{}", data);
        return new JsonResult(StatusCode.THROWABLE_ERROR, data);
    }*/
}
